import { Plugin } from 'vite';
import babel from '@babel/core';
import babelImport from 'babel-plugin-import';
import babelLodash from 'babel-plugin-lodash';

import importMeta from '@babel/plugin-syntax-import-meta';

export const pluginImport = (env?: {
  mode: string
}): Plugin => ({
  name: 'vite-plugin-importer',
  apply: 'build',
  transform(code: string, id: string) {
    if (/\.(?:[jt]sx?)$/.test(id)) {
      const plugins = [
        importMeta,
        // 按需加载 antd
        [babelImport, {
          libraryName: 'antd',
          libraryDirectory: 'es',
          style: true,
        }],
        // 按需加载 lodash
        [babelLodash, { id: ['async', 'lodash-bound'] }]
      ];

      const result = babel.transformSync(code, {
        ast: true,
        plugins,
        sourceFileName: id
      });

      return {
        code: result.code,
        map: result.map
      };
    }

    return undefined;
  },
});

/**
 * 转换index.html
 * @param publicUrl
 * @returns
 */
export const htmlPlugin = (): Plugin => ({
  name: 'html-transform',
  apply: 'build',
  enforce: 'post',
  transformIndexHtml(html: string) {
    let htmlText = html;

    // 将vite 默认打包的js放到body前
    const jsMatchs = html.match(/<script type="module".*?<\/script>/g);
    if (jsMatchs?.length) {
      htmlText = html.replace(/<script type="module".*?<\/script>/g, '').replace(/<\/body>/, `\t${jsMatchs.join('\t\n')}\n$&`);
    }

    return htmlText;
  },
});
